package com.david.fastmsg.service.impl;

import cn.hutool.core.net.NetUtil;
import com.david.fastmsg.Constant.Constant;
import com.david.fastmsg.Constant.Param;
import com.david.fastmsg.enums.ResponseEnum;
import com.david.fastmsg.exception.RespException;
import com.david.fastmsg.modal.*;
import com.david.fastmsg.repository.*;
import com.david.fastmsg.service.FriendService;
import com.david.fastmsg.service.GroupService;
import com.david.fastmsg.utils.Config;
import com.david.fastmsg.utils.JsonUtils;
import com.david.fastmsg.utils.ResponseUtils;
import com.david.fastmsg.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author qzw
 * @date 2021/9/6
 */
@Service
public class GroupServiceImpl implements GroupService {

    @Autowired
    private RoomRepository roomRepository;

    @Autowired
    private ChatRepository chatRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private Config config;

    @Override
    public Map<String, Object> createGroup(String groupName, String chatList) {
        Room room = new Room();
        room.setRoomId(Utils.getRoomId());
        room.setRoomName(groupName);
        List<String> userIdList = JsonUtils.stringToList(chatList);
        List<Users> userAll = userRepository.findAllByUserIdList(userIdList);
        String appendGroupName = "";
        List<String> userPicList = new ArrayList<>();
        for (Users user: userAll) {
            appendGroupName += user.getUserName() + ",";
            userPicList.add(user.getPicSmall());
        }
        if (StringUtils.isEmpty(groupName)) {
            if (appendGroupName.length() >= 10) {
                room.setRoomName(appendGroupName.substring(0, 10) + "...");
            } else {
                room.setRoomName(appendGroupName.substring(0, appendGroupName.length()-1));
            }
        }
        String groupPic = Constant.HTTP + NetUtil.getLocalhost().getHostAddress() + ":" + config.getServerPort()
                + Utils.generateGroupHead(userPicList);
        room.setRoomPicSmall(groupPic);
        room.setCreateTime(new Date());
        roomRepository.save(room);
        Chat chat = new Chat();
        chat.setRoomId(room.getRoomId());
        chat.setChatList(chatList);
        chat.setIsGroup(1);
        chat.setCreateTime(new Date());
        chatRepository.save(chat);
        Map<String, Object> success = ResponseUtils.success();
        success.put(Param.ROOM_ID, room.getRoomId());
        success.put(Param.ROOM_NAME, room.getRoomName());
        success.put(Param.IS_GROUP, chat.getIsGroup());
        return success;
    }
}
